package com.mall.shopping.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.commons.tool.redisconfig.RedissonAutoConfiguration;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartProductConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.*;

/**
 * @ClassName CartServiceImpl
 * @Description
 * @Author 王昀昊
 * @Date 2021/8/24 22:14
 * @Version 1.0
 **/
@Service
@Slf4j
@Component
public class CartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartProductConverter cartProductConverter;

    /**
     * 获得购物车列表
     * @param request
     * @return
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            // 校验请求参数的有效性
            request.requestCheck();
            // 查询数据库
            String userId = String.valueOf(request.getUserId());
            RMap<Long, CartProductDto> map = redissonClient.getMap(userId);
            Set<Long> keySet = map.keySet();
            List<CartProductDto> values = new ArrayList<>();
            for (Long key : keySet) {
                values.add(map.get(key));
            }
//            Set<Map.Entry<Integer, CartProductDto>> entrySet = map.entrySet();
//            for (Map.Entry<Integer, CartProductDto> integerCartProductDtoEntry : entrySet) {
//                System.out.println(integerCartProductDtoEntry);
//            }
//            List<CartProductDto> values = (List<CartProductDto>) map.values();

            response.setCartProductDtos(values);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return response;
    }

    /**
     * 添加商品到购物车
     * @param addCartRequest
     * @return
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest addCartRequest) {
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            addCartRequest.requestCheck();
            //连接数据库
            String userId = String.valueOf(addCartRequest.getUserId());
            RMap<Long, CartProductDto> map = redissonClient.getMap(userId);
            //先判断该商品是否已经添加到购物车
            CartProductDto itemCart = map.get(addCartRequest.getItemId());
            if (itemCart != null){
                //说明购物车中已存在该商品，只需要数量增加相应的数量即可
                itemCart.setProductNum(itemCart.getProductNum() + addCartRequest.getNum());
                map.put(addCartRequest.getItemId(), itemCart);
                addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
                addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
                return addCartResponse;
            }
            //运行到这里说明购物车中没有添加该商品
            Item item = itemMapper.selectByPrimaryKey(addCartRequest.getItemId());
            CartProductDto cartProductDto = cartProductConverter.item2Dto(item);
            cartProductDto.setChecked("true");
            cartProductDto.setProductNum((long) addCartRequest.getNum());
            String image = item.getImage();
            String[] split = image.split(",");
            if (split.length == 0){
                throw new ValidateException("参数异常");
            }
            cartProductDto.setProductImg(split[0]);
            map.put(addCartRequest.getItemId(), cartProductDto);
            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (ValidateException e) {
            addCartResponse.setCode(e.getErrorCode());
            addCartResponse.setMsg(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            addCartResponse.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            addCartResponse.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
        }
        return addCartResponse;
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {

        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            request.requestCheck();
            //get the cart database from redisson
            RMap<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            //judge the checked status and set checked'value

            CartProductDto cartProductDto = map.get(request.getItemId());
            cartProductDto.setChecked(request.getChecked());

            int num = request.getNum();
            cartProductDto.setProductNum(Long.valueOf(num));

            map.remove(request.getItemId());
            map.put(request.getItemId(),cartProductDto);
            

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("CartServiceImpl.updateCartNum occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        CheckAllItemResponse response = new CheckAllItemResponse();

        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            //修改所有的状态
            Set<Long> integers = map.keySet();
            for (Long feild : integers) {
                CartProductDto dto = map.get(feild);
                dto.setChecked(request.getChecked());

                map.remove(feild);
                map.put(feild,dto);
            }
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("CartServiceImpl.checkAllCartItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        DeleteCartItemResponse response = new DeleteCartItemResponse();
        try {
            request.requestCheck();
            RMap<Object, Object> map = redissonClient.getMap(request.getUserId().toString());
            map.remove(request.getItemId());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("CartServiceImpl.deleteCartItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        DeleteCheckedItemResposne response = new DeleteCheckedItemResposne();

        try {
            request.requestCheck();
            RMap<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            //遍历map对于checked为true的item删除
            Set<Long> integers = map.keySet();
            for (Long feild : integers) {
                CartProductDto dto = map.get(feild);
                if (dto.getChecked().equals("true")) {
                    map.remove(feild);
                }
            }

            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("CartServiceImpl.deleteCheckedItem occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
